import { Algorithm } from "../types"

// 数据模型定义
interface MPLPNode {
  id: any
  type: string
  attributes: Record<string, any>
}

interface MPLPEdge {
  source: any
  target: any
  type?: string
  weight?: number
  attributes: Record<string, any>
}

interface MPLPGraph {
  nodes: MPLPNode[]
  edges: MPLPEdge[]
}

// 定义时序图数据结构
interface TemporalGraph {
  nodes: MPLPNode[]
  edges: MPLPEdge[]
  timestamp: string
}

// 修改任务状态枚举
enum TaskStatus {
  PENDING = "PENDING",
  RUNNING = "RUNNING", 
  COMPLETED = "COMPLETED",
  FAILED = "FAILED"
}

// 修改接口定义以匹配后端schema
interface TSGEInputParams {
  graph_sequence: Array<{
    nodes: MPLPNode[];
    edges: MPLPEdge[];
  }>;
  embedding_dim: number;
  learning_rate: number;
  epochs: number;
  node_types?: Record<string, string>;
}

interface NodeEmbedding {
  node_id: string;
  embedding: number[];
  node_type?: string;
}

interface LinkPrediction {
  source: string;
  target: string;
  probability: number;
  time?: number;
}

interface TSGEOutputParams {
  node_embeddings: NodeEmbedding[];
  link_predictions?: LinkPrediction[];
  algorithm: string;
  parameters: Record<string, any>;
  train_loss_history?: number[];
}

interface TSGERequestParams {
  tsge_params: TSGEInputParams;
}

interface DRPAInputParams {
  data_flows: Array<Record<string, any>>;
  time_window: number;
  risk_threshold: number;
  sensitivity_weights: {
    data_type: number;
    access_frequency: number;
    user_privilege: number;
    historical_incidents: number;
  };
}

interface WindowAssessment {
  window_id: number;
  start_time: number;
  end_time: number;
  risk_score: number;
  risk_level: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
  flagged_flows: string[];
  mitigation_actions: string[];
}

interface DRPAOutputParams {
  assessments: WindowAssessment[];
  overall_risk_score: number;
  high_risk_patterns: Array<Record<string, any>>;
  recommended_actions: string[];
}

interface DRPARequestParams {
  drpa_params: DRPAInputParams;
}

interface MedicalShareInputParams {
  data_parties: DataPartyInfo[];
  objective_weights: {
    PRIVACY: number;
    UTILITY: number;
    FAIRNESS: number;
    EFFICIENCY: number;
  };
  max_iterations: number;
  convergence_threshold: number;
  privacy_threshold: number;
}

interface MedicalShareRequestParams {
  medical_share_params: MedicalShareInputParams;
}

interface InputParams {
  tsge_params: TSGEInputParams;
}

interface OutputParams {
  tsge_results: TSGEOutputParams;
}

interface AlgorithmRequest {
  task_id: string;
  task_callback_url?: string;
  input_params: TSGERequestParams | DRPARequestParams | MedicalShareRequestParams;
}

interface TSGEResponseParams {
  tsge_results: TSGEOutputParams;
}

interface DRPAResponseParams {
  drpa_results: DRPAOutputParams;
}

interface MedicalShareResponseParams {
  medical_share_results: any;
}

interface AlgorithmResponse {
  task_id: string;
  task_callback_url?: string;
  task_status: TaskStatus;
  task_progress: number;
  task_logs?: string;
  error_message?: string;
  output_params: TSGEResponseParams | DRPAResponseParams | MedicalShareResponseParams;
  metrics: any[]; // 这里可以根据Chart类型进一步定义
}

// 更新接口定义
interface DataPartyInfo {
  party_id: string;
  data_size: number;
  data_types: string[];
  privacy_budget: number;
  min_share_ratio: number;
}

// 修改算法实现
export const MedicalShareService: Algorithm = {
  name: "医疗数据共享优化算法",
  description: "基于多目标优化的医疗数据共享策略生成算法",
  configOptions: [
    {
      id: "data_parties",
      label: "数据参与方信息",
      type: "textarea",
      defaultValue: JSON.stringify([
        {
          party_id: "hospital_1",
          data_size: 1000,
          data_types: ["patient_records", "lab_results"],
          privacy_budget: 1.0,
          min_share_ratio: 0.3
        }
      ], null, 2),
      placeholder: "请输入数据参与方信息的JSON数组"
    },
    {
      id: "objective_weights",
      label: "目标权重配置",
      type: "textarea",
      defaultValue: JSON.stringify({
        PRIVACY: 0.4,
        UTILITY: 0.3,
        FAIRNESS: 0.2,
        EFFICIENCY: 0.1
      }, null, 2),
      placeholder: "请输入目标权重配置的JSON对象"
    },
    {
      id: "max_iterations",
      label: "最大迭代次数",
      type: "number",
      defaultValue: 100,
      placeholder: "100"
    },
    {
      id: "convergence_threshold",
      label: "收敛阈值",
      type: "number",
      defaultValue: 0.001,
      placeholder: "0.001"
    },
    {
      id: "privacy_threshold",
      label: "隐私保护阈值",
      type: "number",
      defaultValue: 0.8,
      placeholder: "0.8"
    }
  ],

  execute: async (config) => {
    try {
      const taskId = `medical_share_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      
      // 解析配置
      const dataParties = JSON.parse(config.data_parties);
      const objectiveWeights = JSON.parse(config.objective_weights);

      const requestData: AlgorithmRequest = {
        task_id: taskId,
        task_callback_url: "http://172.16.4.151:1122/api/medical_share/callback",
        input_params: {
          medical_share_params: {
            data_parties: dataParties,
            objective_weights: objectiveWeights,
            max_iterations: Number(config.max_iterations),
            convergence_threshold: Number(config.convergence_threshold),
            privacy_threshold: Number(config.privacy_threshold)
          }
        }
      };

      // 创建任务
      const createResponse = await fetch("http://172.16.4.151:1122/api/medical_share/create", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(requestData)
      });

      if (!createResponse.ok) {
        const errorData = await createResponse.json();
        throw new Error(errorData.detail || "创建任务失败");
      }

      // 执行任务
      const executeResponse = await fetch(`http://172.16.4.151:1122/api/medical_share/execute/${taskId}`, {
        method: "POST"
      });

      if (!executeResponse.ok) {
        const errorData = await executeResponse.json();
        throw new Error(errorData.detail || "执行任务失败");
      }

      // 轮询获取结果
      let result;
      let attempts = 0;
      const maxAttempts = 60;

      while (attempts < maxAttempts) {
        const getResultResponse = await fetch(`http://172.16.4.151:1122/api/medical_share/result/${taskId}`);
        
        if (!getResultResponse.ok) {
          const errorData = await getResultResponse.json();
          throw new Error(errorData.detail || "获取结果失败");
        }

        result = await getResultResponse.json();
        
        if (result.task_status === TaskStatus.COMPLETED) {
          break;
        } else if (result.task_status === TaskStatus.FAILED) {
          throw new Error(result.error_message || "任务执行失败");
        }

        await new Promise(resolve => setTimeout(resolve, 1000));
        attempts++;
      }

      if (attempts >= maxAttempts) {
        throw new Error("任务执行超时");
      }

      const outputParams = result.output_params.medical_share_results;
      
      // 生成结果摘要
      const resultText = `医疗数据共享优化完成：
算法: ${outputParams.algorithm}
最终策略数量: ${outputParams.final_strategies.length}
迭代次数: ${outputParams.results.length}

最终共享策略:
${outputParams.final_strategies.map((strategy: any) => `
参与方 ${strategy.party_id}:
- 共享比例: ${(strategy.share_ratio * 100).toFixed(2)}%
- 隐私得分: ${strategy.privacy_score.toFixed(3)}
- 选定特征数: ${strategy.selected_features.length}个
`).join('\n')}`;

      return {
        result: resultText,
        steps: outputParams.results.map((step: any) => 
          `迭代 ${step.iteration}: 目标得分 - ${JSON.stringify(step.objective_scores)}`
        ),
        executionTime: 0,
        details: {
          algorithm: outputParams.algorithm,
          finalStrategies: outputParams.final_strategies.map((strategy: any) => ({
            partyId: strategy.party_id,
            shareRatio: (strategy.share_ratio * 100).toFixed(2) + '%',
            privacyScore: strategy.privacy_score.toFixed(3),
            selectedFeaturesCount: strategy.selected_features.length
          })),
          iterationCount: outputParams.results.length,
          convergenceHistory: outputParams.convergence_history || []
        }
      };
    } catch (e: any) {
      console.error("医疗数据共享算法执行出错:", e);
      throw e;
    }
  }
}; 